using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Linq;
using ZedGraph;
using System.Diagnostics;
using System.Runtime.InteropServices;
using  Crom.Controls.Docking;

 
namespace UI
{
     
    public partial class FrmMain : Form
    {
        private System.Windows.Forms.OpenFileDialog openFileDialog1;

        public string ScenarioFile
        {
            get
            {
                return Properties.Settings.Default.ScenarioFile;
            }
            set
            {
                Properties.Settings.Default.ScenarioFile = value;
                Properties.Settings.Default.Save();
            }
        }
         FrmTXTDisplay progress;
            

        public FrmMain()
        {
            InitializeComponent();
            this.WindowState = FormWindowState.Maximized;

            AddLogFrm();
        }
        void AddLogFrm()
        {
            progress = new FrmTXTDisplay("Log", null);

            DockableFormInfo d = this.dockContainer2.Add(progress, zAllowedDock.Right, Guid.NewGuid());

            dockContainer2.DockForm(d, DockStyle.Right, zDockMode.Outer);

            dockContainer2.SetAutoHide(d, true);
        }
        string outputdir
        {
            get
            {
                return Path.GetDirectoryName(ScenarioFile) + "\\output";
            }
        }


        
       
        public void RunLandis()
        {
            Process[] processlist = Process.GetProcesses();

            foreach (Process theprocess in processlist)
            {
                if (theprocess.ProcessName.Contains("Landis.Console"))
                {
                    theprocess.Kill();
                }
            }

            System.IO.Directory.SetCurrentDirectory(Path.GetDirectoryName(ScenarioFile));

            string OutputDirectory = Path.Combine(Path.GetDirectoryName(ScenarioFile), "output");

            Directory.DeleteDirectory(OutputDirectory);

            System.IO.Directory.CreateDirectory(OutputDirectory);


            FrmSimulation ow = new FrmSimulation(ScenarioFile, new string[] { Path.Combine(System.IO.Path.GetDirectoryName(ScenarioFile), "output") });
            Crom.Controls.Docking.DockableFormInfo df = dockContainer2.Add(ow, Crom.Controls.Docking.zAllowedDock.All, Guid.NewGuid());
            dockContainer2.DockForm(df, DockStyle.Fill, Crom.Controls.Docking.zDockMode.Inner);

            foreach (string file in Directory.GetAllFiles("output")) System.IO.File.Delete(file);

            string path = Environment.GetEnvironmentVariable("PATH");

            string newPath = "C:\\Program Files\\LANDIS-II\\GDAL\\1.9;" + path;

            Environment.SetEnvironmentVariable("PATH", newPath);

            if (System.IO.File.Exists(ScenarioFile))
            {
                string FileName = "C:\\Program Files\\LANDIS-II\\v6\\bin\\Landis.Console-6.0.exe";

                if (System.IO.File.Exists(FileName) == false)
                {
                    FileName = "C:\\Program Files\\LANDIS-II\\v6\\bin\\Landis.Console-6.1.exe";
                }
                if (System.IO.File.Exists(FileName) == false)
                {
                    throw new System.Exception("No file called " + FileName);
                }

                System.Diagnostics.Process simulation = new System.Diagnostics.Process();

                simulation.StartInfo.FileName = FileName;

                simulation.StartInfo.CreateNoWindow = true;
                simulation.StartInfo.UseShellExecute = false;
                simulation.StartInfo.RedirectStandardOutput = true;

                FrmTXTDisplay simulation_log_form = new FrmTXTDisplay(FileName, simulation);

                DockableFormInfo simulation_log_form_info = this.dockContainer2.Add(simulation_log_form, zAllowedDock.All, Guid.NewGuid());

                dockContainer2.DockForm(simulation_log_form_info, DockStyle.Right, Crom.Controls.Docking.zDockMode.None);

                simulation.StartInfo.Arguments = "\"" + ScenarioFile + "\"";

                simulation.Start();

                simulation.BeginOutputReadLine();
            }
            
        }
        
        private void button1_Click(object sender, EventArgs e)
        {
            ShowFilesInFile(ScenarioFile);
        }
        public string[] InputFiles()
        {
            return InputFiles(ScenarioFile);
        }
        public string[] InputFiles(string ScenarioFileName)
        {
            List<string> inputfiles = new List<string>();
            if (System.IO.File.Exists(ScenarioFileName))
            {
                string[] content = System.IO.File.ReadAllLines(ScenarioFileName);
                foreach (string line in content)
                {
                    if (line.Contains(">>")) line.Remove(line.IndexOf(">>"));
                    string[] terms = line.Split(new char[] { ',', '\t', ' ' }, System.StringSplitOptions.RemoveEmptyEntries);
                    foreach (string term in terms)
                    {
                        if (term.Contains(".txt") && System.IO.File.Exists(term))
                        {
                            if (inputfiles.Contains(term) == false) inputfiles.Add(term);
                            
                            
                            string[] Files = InputFiles(term);
                            foreach (string File in Files)
                            {
                                if (inputfiles.Contains(File) == false) inputfiles.Add(File);
                                
                            }
                        }
                    }
                }
            }

             return inputfiles.ToArray();
        }
        private void ShowFilesInFile(string ScenarioFileName)
        {
            if (System.IO.File.Exists(ScenarioFileName))
            {
                System.Diagnostics.Process.Start("NotePad", ScenarioFileName);

                foreach (string File in InputFiles(ScenarioFileName))
                {
                    System.Diagnostics.Process.Start("NotePad", File);
                }
            }
        }
         
        
        Crom.Controls.Docking.DockableFormInfo df =null;
        FrmSelectFiles dlg;

        private void AddData()
        {
            if (df != null)
            {
                if (dlg != null)
                {
                    dlg.Close();
                    dlg = null;
                }
           
            }
            dlg = new FrmSelectFiles();

            dlg.MyFormClosing += OpenFrmSimulation;

            dlg.InitialDirectory = "";

            df = dockContainer2.Add(dlg, Crom.Controls.Docking.zAllowedDock.Top, Guid.NewGuid());
            dockContainer2.DockForm(df, DockStyle.Top, Crom.Controls.Docking.zDockMode.Inner);

           
        
        }
        private void OpenFrmSimulation(object sender, EventArgs e)
        {
            if (df != null)
            {
                this.dockContainer2.Remove(df);
                df = null;
            }

            FrmSelectFiles dlg = (FrmSelectFiles)sender;

            string[] FilesFolders = dlg.Selection.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            // Get all folders
            List<string> Folders = new List<string>(FilesFolders.Where(o => System.IO.Directory.Exists(o)));
            foreach (string Folder in Folders)
            {
                FrmSimulation simulation_form = new FrmSimulation(Folder, System.IO.Directory.GetFiles(Folder));

                simulation_form.SendMessage += progress.Append;

                Crom.Controls.Docking.DockableFormInfo simulation_form_info = dockContainer2.Add(simulation_form, Crom.Controls.Docking.zAllowedDock.All, Guid.NewGuid());
                dockContainer2.DockForm(simulation_form_info, DockStyle.Fill, Crom.Controls.Docking.zDockMode.Inner);

            }
            // Get all single files
            List<string> Files = new List<string>(FilesFolders.Where(o => System.IO.File.Exists(o)));
            if (Files.Count() > 0)
            {
                FrmSimulation simulation_form = new FrmSimulation("Output window"  ,Files.ToArray());
                Crom.Controls.Docking.DockableFormInfo simulation_form_info = dockContainer2.Add(simulation_form, Crom.Controls.Docking.zAllowedDock.All, Guid.NewGuid());
                dockContainer2.DockForm(simulation_form_info, DockStyle.Fill, Crom.Controls.Docking.zDockMode.Inner);

            }


        }

        private void toolBar1_ButtonClick(object sender, ToolBarButtonClickEventArgs e)
        {
            string tag = (string)e.Button.Tag;
            switch (tag)
            {
                case "Add":
                    AddData();
                    break;
                case "Clear":
                    dockContainer2.Clear();
                    AddLogFrm();
                    break;
                case "Run":
                    openFileDialog1 = new OpenFileDialog();
                    openFileDialog1.InitialDirectory = ScenarioFile;
                    DialogResult result = openFileDialog1.ShowDialog();
                    if (result == DialogResult.OK)
                    {
                        ScenarioFile = openFileDialog1.FileName;
                        RunLandis();
                    }
                    break;
                case "Rerun":
                    RunLandis();
                    break;
                case "SimulationFiles":
                    ShowFilesInFile(ScenarioFile);
                    break;
                
                    
            }
        }



        
        
         

    }
}